package servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import connection.DbConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.StringTokenizer;

import model.EmailingSystem;
import model.PollUserImpl;
import bean.PollUser;
import bean.User_Device;

public class addDeviceServlet extends HttpServlet {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = -5974196197537527180L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost (request, response);
	}
	
	public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("GBK");
		
		System.out.println("addDeviceServlet run");
		
		//Get parameters
		String add_device_id = request.getParameter("add_device");
		String username = request.getSession().getAttribute("username").toString();
		
		// Error checking
		System.out.println("added_device_id: "+add_device_id);
		System.out.println("username: "+username);
		
		// Create User_device bean
		User_Device ud = new User_Device();
		ud.setPollUsername(username);
		ud.setDeviceId(add_device_id);
		
		// Add to database
		DbConnection db = new DbConnection();
		String sql = "Insert into User_Device Values ('"+ud.getPollUsername()+"','"+ud.getDeviceId()+"')";
		System.out.println(sql);
		db.doInsert(sql);

		// Clear other success messages
		request.getSession().setAttribute("settings_change_personal_success", "f");
		request.getSession().setAttribute("settings_success", "f");
		request.getSession().setAttribute("settings_incorrect_pw", "f");
		request.getSession().setAttribute("settings_delete_device_success","f");
		
		// Set new success message
		request.getSession().setAttribute("settings_add_device_success","t");
		
		// Send back
		response.sendRedirect("settings.jsp");
	}
}
